<?php
// 数据库配置
define('DB_HOST', 'localhost');
define('DB_USER', 'yy');
define('DB_PASS', 'ym6YyGK453yYdCJL');
define('DB_NAME', 'personnel_status');

// 创建数据库连接
function getDBConnection() {
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($conn->connect_error) {
        die("数据库连接失败: " . $conn->connect_error);
    }
    return $conn;
}

// 初始化数据库表
function initDatabase() {
    $conn = getDBConnection();
    
    // 创建用户表
    $sql = "CREATE TABLE IF NOT EXISTS users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(50) NOT NULL UNIQUE,
        password VARCHAR(255) NOT NULL,
        department VARCHAR(50) NOT NULL,
        role ENUM('admin', 'department') NOT NULL
    )";
    $conn->query($sql);
    
    // 创建人员表
    $sql = "CREATE TABLE IF NOT EXISTS personnel (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(50) NOT NULL UNIQUE,
        department VARCHAR(50) NOT NULL,
        status VARCHAR(20) DEFAULT '在位',
        note TEXT
    )";
    $conn->query($sql);
    
    // 创建状态历史表
    $sql = "CREATE TABLE IF NOT EXISTS status_history (
        id INT AUTO_INCREMENT PRIMARY KEY,
        personnel_id INT NOT NULL,
        name VARCHAR(50) NOT NULL,
        old_status VARCHAR(20),
        new_status VARCHAR(20) NOT NULL,
        note TEXT,
        changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        is_deleted BOOLEAN DEFAULT FALSE
    )";
    $conn->query($sql);
    
    // 添加默认管理员
    $sql = "INSERT IGNORE INTO users (username, password, department, role) 
            VALUES ('admin', '".password_hash('123456', PASSWORD_DEFAULT)."', 'admin', 'admin')";
    $conn->query($sql);
    
    $conn->close();
}

// 初始化数据库
initDatabase();
?>